<template>
  <view class="member-page">
    <!-- 顶部渐变区域 -->
    <view class="top-gradient-section">
      <!-- 状态栏占位 -->
      <view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
      <!-- 用户信息区域 -->
      <view class="user-profile-section" v-if="token && userInfo">
        <!-- 已登录状态 -->
        <view class="user-info">
          <view class="avatar-container" style="margin-right:22rpx">
            <image class="user-avatar" :src="userInfo.head_imgurl || '/static/images/avatar.png'" mode="aspectFill"></image>
          </view>
          <view class="user-details">
            <view class="phone-number">{{ userInfo.nickname || userInfo.phone || '138****1234' }}</view>
            <view class="user-id-row">
              <text class="user-id">ID:{{ userInfo.to_Account || '12345678' }}</text>
              <!--
              <view class="level-badge">
                <text class="level-icon">💰</text>
                <text class="level-text">Lv.{{ userInfo.level || '4' }}</text>
              </view>
              -->
              <view class="settings-icon" @click="goSettings">
                <image src="/static/images/设置.png" class="settings-image" />
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 未登录状态 -->
      <view class="login-prompt" v-if="!token || !userInfo">
        <view class="login-avatar">
          <image class="user-avatar" src="/static/images/avatar.png" mode="aspectFill"></image>
        </view>
        <view class="login-info">
          <view class="login-title">Hello！</view>
          <view class="login-desc">登录领取会员卡享更多权益</view>
        </view>
        <view class="login-btn" @click="goLogin">
          <text>注册/登录</text>
        </view>
      </view>

      <view class="vip-banner">
        <view class="vip-info">
          <image src="/static/images/Mask group1@2x.png" class="vip-image" />
          <text class="vip-text">利行VIP每月最高可省 250 元</text>
        </view>
        <view class="vip-btn" @click="goVip">
          <text>去开通</text>
        </view>
      </view>
    </view>

    <!-- 底部纯色区域 -->
    <view class="bottom-solid-section">
      <view class="section-position">
        <!-- 账户概览卡片 -->
        <view class="account-overview-card" v-if="token && userInfo">
          <view class="overview-item">
            <text class="overview-value" :class="{ 'loading-text': isLoading }">
              {{ isLoading ? '加载中...' : '¥' + (userInfo.chargeBalance || '0.00') }}
            </text>
            <text class="overview-label">充电余额</text>
          </view>
          <view class="quick-divider"></view>
          <view class="overview-item">
            <text class="overview-value" :class="{ 'loading-text': isLoading }">
              {{ isLoading ? '加载中...' : '¥' + (userInfo.walletMoneyString || '0.00') }}
            </text>
            <text class="overview-label">余额</text>
          </view>
          <view class="quick-divider"></view>
          <view class="overview-item" @click="goToCoupon">
            <text class="overview-value" :class="{ 'loading-text': isLoading }">
              {{ isLoading ? '加载中...' : (userInfo.validMealTicket || '0') }}
            </text>
            <text class="overview-label">我的卡券</text>
          </view>
          <view class="quick-divider"></view>
          <view class="overview-item">
            <text class="overview-value" :class="{ 'loading-text': isLoading }">
              {{ isLoading ? '加载中...' : (userInfo.allIntegral || '0') }}
            </text>
            <text class="overview-label">我的积分</text>
          </view>
        </view>
        
        <!-- 未登录时的提示 -->
        <view class="login-required-card" v-else>
          <view class="login-required-content">
            <uni-icons type="info" size="48" color="#ff7b3a"></uni-icons>
            <text class="login-required-text">登录后查看账户信息</text>
            <view class="login-required-btn" @click="goLogin">
              <text>立即登录</text>
            </view>
          </view>
        </view>

        <!-- 快捷功能区域 -->
        <view class="quick-access-card">
          <view class="quick-item" @click="goRechargeOrder">
            <image src="/static/images/dingdan@2x.png" class="quick-icon" />
            <text class="quick-text">充电订单</text>
          </view>
          <view class="quick-item" @click="goFavorites">
            <image src="/static/images/shoucang@2x.png" class="quick-icon" />
            <text class="quick-text">收藏</text>
          </view>
          <view class="quick-item" @click="goPrepaidDetails">
            <image src="/static/images/mingxi@2x.png" class="quick-icon" />
            <text class="quick-text">预付费明细</text>
          </view>
          <view class="quick-item" @click="goVip">
            <image src="/static/images/vip@2x.png" class="quick-icon" />
            <text class="quick-text">VIP</text>
          </view>
        </view>

        <!-- 利行司机驿站陪伴 -->
        <view v-if="token" class="charging-card">
          <view class="section-title">
            利行司机驿站陪伴您625天
          </view>
          <view class="charging-rows">
            <view class="charging-item">
              <text class="charging-num">128</text>
              <view class="charging-text">充电度数(度)</view>
            </view>
            <view class="charging-item">
              <text class="charging-num">265</text>
              <view class="charging-text">充电金额(元)</view>
            </view>
            <view class="charging-item">
              <text class="charging-num" style="color:#FF6600">50.1	</text>
              <view class="charging-text">优惠金额(元)</view>
            </view>
          </view>
        </view>

        <!-- 我的爱车区域 -->
        <view class="my-car-section">
          <view class="section-title">
            我的爱车{{ currentCarIndex < actualCarCount ? `（${currentCarIndex + 1}/${actualCarCount}）` : '' }}
          </view>
          <view class="car-swiper-container">
            <uni-swiper-dot
              :info="displayedCars"
              :current="currentCarIndex"
              :total="totalCarCount"
              @change="onSwiperChange"
              :dotsStyles="{selectedBackgroundColor: displayedCars.length == 1 ? '#ffffff' :'#333'}"
            >
              <swiper 
                class="car-swiper" 
                :current="currentCarIndex" 
                @change="onSwiperChange"
                :indicator-dots="false"
                :autoplay="false"
                :circular="false"
              >
                <swiper-item v-for="(item, idx) in displayedCars" :key="idx">
                  <view class="car-card" @click="handleCarClick(item)">
                    <view class="add-car-icon" v-if="item && item.type === 'add'">
                      <text class="plus-icon">+</text>
                    </view>
                    <view class="car-info" :class="{ 'car-info-with-icon': item && item.type === 'add' }">
                      <text class="car-title">{{ (item && item.carNumber) || (item && item.title) || '' }}</text>
                      <text class="car-desc">{{ (item && item.desc) || '' }}</text>
                    </view>
                    <!-- 为除了添加车辆之外的所有轮播图添加Mask group@2x图片 -->
                    <view class="car-mask-icon" v-if="!(item && item.type === 'add')">
                      <image src="https://app-1306761403.cos.accelerate.myqcloud.com/lx-images/Mask_group@2x.png" class="mask-image" />
                    </view>
                  </view>
                </swiper-item>
              </swiper>
            </uni-swiper-dot>
          </view>
        </view>
      </view>
    </view>

    <!-- 智能Tabbar -->
    <smart-tabbar ref="smartTabbar"></smart-tabbar>
  </view>
</template>

<script>
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import uniSwiperDot from '@/uni_modules/uni-swiper-dot/components/uni-swiper-dot/uni-swiper-dot.vue'
import SmartTabbar from '@/components/smart-tabbar/index.vue'
import { getInfo } from '@/api/index/index.js'
import { getMyCarList } from '@/api/charging/index.js'

export default {
  components: {
      SmartTabbar,
      uniIcons,
      uniSwiperDot
  },
  data() {
      return {
          statusBarHeight: 0,
          userInfo: null, // 用户信息
          token: null, // 登录token
          isLoading: false, // 加载状态
          // 车辆列表
          carList: [],
          currentCarIndex: 0, // 当前显示的车牌索引
          totalCarCount: 0 // 总车辆数
      };
  },
  onLoad(options) {
      // 获取token
      this.token = uni.getStorageSync('token') || null;
      // 获取状态栏高度
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight
      console.log(this.statusBarHeight,'this.statusBarHeight高度')
  },
  onShow() {
      this.token = uni.getStorageSync('token') || null;
      
      // 获取车辆列表
      this.getCarList();
      
      // 如果有token，获取用户信息
      if (this.token) {
          this.getUserInfo();
      }
      
      // 车辆列表不需要每次都刷新，避免重复调用接口
      // 只有在特定情况下才需要刷新，比如从添加车辆页面返回
  },
  methods: {
      // 获取用户信息
      getUserInfo() {
          console.log('获取用户信息');
          this.isLoading = true;
          
          getInfo().then((res) => {
              console.log('用户信息接口返回:', res);
              this.isLoading = false;
              
              if (res.code === 0 && res.success) {
                  // 保存用户信息到本地存储
                  uni.setStorageSync('userInfo', res.data);
                  this.userInfo = res.data;
                  console.log('用户信息更新成功:', this.userInfo);
              } else {
                  console.error('获取用户信息失败:', res.msg);
                  uni.showToast({
                      title: res.msg || '获取用户信息失败',
                      icon: 'none'
                  });
              }
          }).catch((err) => {
              console.error('用户信息接口错误:', err);
              this.isLoading = false;
              uni.showToast({
                  title: '网络请求失败',
                  icon: 'none'
              });
          });
      },
      // 获取车辆列表
      getCarList() {
          getMyCarList().then(res => {
              console.log('我的车牌列表返回：', res);
              if (res && res.success && res.data && Array.isArray(res.data.records)) {
                  // 根据isDefault字段重新排列列表，默认车辆放在最前面
                  const sortedCarList = [...res.data.records];
                  const defaultIndex = sortedCarList.findIndex(car => car.isDefault === true);
                  
                  if (defaultIndex > 0) {
                      // 找到默认车辆，将其移到最前面
                      const defaultCar = sortedCarList.splice(defaultIndex, 1)[0];
                      sortedCarList.unshift(defaultCar);
                  }
                  
                  // 仅取前5个显示
                  this.carList = sortedCarList.slice(0, 5);
                  this.totalCarCount = this.carList.length;
                  console.log('车辆列表更新成功，共', this.carList.length, '辆，默认车辆已排在最前面');
              } else {
                  console.warn('车牌列表返回不包含有效records');
                  this.carList = [];
                  this.totalCarCount = 0;
              }
          }).catch(err => {
              console.error('获取我的车牌列表失败：', err);
              this.carList = [];
              this.totalCarCount = 0;
          });
      },
      
      // 刷新车辆列表（用于从添加车辆页面返回时调用）
      refreshCarList() {
          console.log('手动刷新车辆列表');
          this.getCarList();
      },
      
      // 页面跳转方法
      goSettings() {
          uni.navigateTo({
              url: '/pages/settings/index'
          });
      },
      
      goVip() {
          uni.showToast({
              title: '暂未实现',
              icon: 'none'
          });
      },
      
      goRechargeOrder() {
          uni.navigateTo({
              url: '/pagesOne/orderList/orderList'
          });
      },
      
      goFavorites() {
          uni.showToast({
              title: '暂未实现',
              icon: 'none'
          });
      },
      
      goPrepaidDetails() {
          uni.navigateTo({
              url: '/pages/preFeeDetail/preFeeDetail'
          });
      },
      
      goAddVehicle() {
          uni.navigateTo({
              url: '/pages/addVehicles/index',
              events: {
                  // 监听添加车辆页面返回事件
                  refreshCarList: () => {
                      this.refreshCarList();
                  }
              }
          });
      },

      goToCoupon() {
          uni.navigateTo({
              url: '/pagesOne/coupon/coupon'
          });
      },
      
      goLogin() {
          uni.navigateTo({
              url: '/packages/oldpages/pages/login/index'
          });
      },

      // 轮播图变化时更新当前显示的车牌索引
      onSwiperChange(e) {
          this.currentCarIndex = e.detail.current;
      },

      handleCarClick(item) {
          // 添加空值检查
          if (!item) {
              console.warn('handleCarClick: item is undefined');
              return;
          }
          
          if (item.type === 'add') {
              this.goAddVehicle();
          } else {
              // 如果是已绑定车辆，传递车辆数据到添加车辆页面进行编辑
              const carData = encodeURIComponent(JSON.stringify(item));
              uni.navigateTo({
                  url: `/pages/addVehicles/index?carData=${carData}`,
                  events: {
                      // 监听编辑车辆页面返回事件
                      refreshCarList: () => {
                          this.refreshCarList();
                      }
                  }
              });
          }
      }
  },
  computed: {
      displayedCars() {
          // 过滤掉无效的车辆项
          const validCars = this.carList.filter(car => car && typeof car === 'object');
          const cars = [...validCars];
          
          if (validCars.length < 5) {
              cars.push({ 
                  type: 'add', 
                  title: '添加车辆', 
                  desc: '可享停车费减免快速离场' 
              });
          }
          // 更新总车辆数
          this.totalCarCount = cars.length;
          return cars;
      },
      actualCarCount() {
          // 计算实际绑定车辆数量，不包括"添加车辆"页面
          return this.carList.length;
      }
  }
};
</script>

<style>
view {
  box-sizing: border-box;
  overflow: unset;
}
.member-page {
  background: #fafbf8;
  min-height: 100vh;
  padding-bottom: 120rpx;
  position: relative;
}

/* 顶部渐变区域 */
.top-gradient-section {
  background: linear-gradient(180deg, #01DFAA 50%, #13B09F 100%);
  /* height: 404rpx; */
  padding: 54rpx 24rpx;
  padding-top: 44rpx;
  padding-bottom: 32rpx;
}

/* 底部纯色区域 */
.bottom-solid-section {
  background: #fafbf8;
  position: relative;
}

/* 用户信息区域 */
.user-profile-section {
  margin: 8rpx 32rpx 4rpx 32rpx;
  /* padding: 4rpx 0; */
  border-radius: 16rpx;
  margin-bottom: 14rpx;
}

.user-info {
  display: flex;
  align-items: center;
  position: relative;
}

.login-prompt {
  margin: 20rpx 32rpx;
  padding: 32rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.login-avatar {
  margin-right: 32rpx;
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background: #f0f0f0;
}

.login-info {
  flex: 1;
}

.login-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.login-desc {
  font-size: 24rpx;
  color: #999;
}

.login-btn {
  background: #ff7b3a;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 24rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.user-details {
  flex: 1;
}

.phone-number {
  font-size: 32rpx;
  font-weight: bold;
  /* margin-bottom: 12rpx; */
}

.user-id-row {
  display: flex;
  align-items: center;
  gap: 16rpx;
  justify-content: space-between;
}

.user-id {
  font-size: 24rpx;
  color: #939393;
}

.level-badge {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background: #ffd700;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.level-icon {
  font-size: 24rpx;
}

.level-text {
  font-size: 24rpx;
  color: #8b4513;
  font-weight: bold;
}

.settings-icon {
  margin-left: auto;
  font-size: 40rpx;
  color: #666;
}

.settings-image {
  width: 36rpx;
  height: 33rpx;
}

/* VIP推广横幅 */
.vip-banner {
  margin: 20rpx 32rpx;
  padding: 16rpx 32rpx;
  background: #A8FBEF;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.vip-info {
  display: flex;
  align-items: center;
}

.vip-image {
  width: 40rpx;
  height: 40rpx;
  margin-right: 16rpx;
}

.vip-text {
  font-size: 24rpx;
  color: #8b4513;
  font-weight: bold;
}

.vip-btn {
  background: #fbcb7a;
  color: #7b4f10;
  padding: 8rpx 16rpx;
  border-radius: 24rpx;
  font-size: 24rpx;
  font-weight: bold;
}

/* 账户概览卡片 */
.account-overview-card {
  margin: 20rpx 32rpx;
  padding: 40rpx 32rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
}
.section-position {
  width: 100%;
  position: absolute;
  top: -52rpx;
  left: 0;
  z-index: 0;
  padding-bottom: 120rpx;
}

.overview-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.overview-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.loading-text {
  color: #999;
  font-weight: normal;
}

.overview-label {
  font-size: 24rpx;
  color: #999;
}

/* 快捷功能区域 */
.quick-access-card {
  margin: 20rpx 32rpx;
  padding: 24rpx 32rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.quick-divider {
  width: 2rpx;
  height: 100rpx;
  background: #e5e5e5;
  margin: 0 16rpx;
}

.quick-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50rpx;
  height: 50rpx;
  margin-bottom: 10rpx;
}

.quick-text {
  font-size: 24rpx;
  color: #666;
}
/* 利行陪伴 */
.charging-num{
  font-weight: 600;
  font-size: 36rpx;
  color: #000000;
} 
.charging-text{
  font-size: 24rpx;
  color: #8D96A5;
  line-height: 36rpx;
}  
.charging-card {
  margin: 20rpx 32rpx;
  background: #fff;
  padding: 24rpx 32rpx;
  box-shadow: 0rpx 4rpx 36rpx 0rpx rgba(230,230,230,0.5);
  border-radius: 24rpx;
}
.charging-rows {
  display: flex;
  justify-content: space-between;
  padding: 16rpx 36rpx;
}
.charging-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
/* 我的爱车区域 */
.my-car-section {
  margin: 20rpx 32rpx;
  background: #fff;
  padding: 24rpx 32rpx;
  box-shadow: 0rpx 4rpx 36rpx 0rpx rgba(230,230,230,0.5);
  border-radius: 24rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 24rpx;
}

.car-swiper-container {
  background: #fafbf8;
  border-radius: 16rpx;
  overflow: hidden;
  height: 120rpx;
}

.car-swiper {
  height: 120rpx;
}

.car-card {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 32rpx;
}

.add-car-icon {
  width: 50rpx;
  height: 50rpx;
  background: #13B09F;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
}

.plus-icon {
  font-size: 28rpx;
  color: #fff;
  font-weight: bold;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.car-info {
  flex: 1;
}

.car-info-with-icon {
  margin-left: 24rpx;
}

.car-mask-icon {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.mask-image {
  width: 100rpx;
  height: 56rpx;
}

.car-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
  display: block;
}

.car-desc {
  font-size: 22rpx;
  color: #999;
  display: block;
}

/* 未登录时的提示卡片 */
.login-required-card {
  margin: 20rpx 32rpx;
  padding: 40rpx 32rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.login-required-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24rpx;
}

.login-required-text {
  font-size: 28rpx;
  color: #333;
  margin-top: 16rpx;
  margin-bottom: 24rpx;
}

.login-required-btn {
  background: #ff7b3a;
  color: #fff;
  padding: 12rpx 24rpx;
  border-radius: 24rpx;
  font-size: 28rpx;
  font-weight: bold;
}
</style>
